from rest_framework.views import APIView
from rest_framework.response import Response
from blog.models import User
from blog.utils.jwt_auth import create_token, get_user_id
from django.contrib.auth.hashers import check_password


class LoginView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            user = User.objects.filter(status=1, username=username).first()

            if not user:
                return Response({'status': 404, 'msg': '账号或密码不正确'})
            if user.is_admin == 1:
                if check_password(password, user.password):
                    token = create_token({'id': user.id, 'username': username})
                    data = {'id': user.id, 'name': user.name, 'Authorization': token}
                    return Response({'status': 200, 'msg': '登陆成功', 'data': data})
                else:
                    return Response({'status': 404, 'msg': '账号或密码不正确'})
            else:
                return Response({'status': 404, 'msg': '用户权限不足'})
        except Exception as e:
            # print(e.args)
            return Response({'status': 204, 'msg': '遇到了异常错误', 'error': e.args})


class GetMyView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')
            id = get_user_id(token)
            user = User.objects.filter(status=1, id=id).first()
            data = {'username': user.username, 'name': user.name, 'tel': user.tel, 'email': user.email}
            return Response({
                'status': 200,
                'msg': '获取成功',
                'data': data
            })
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'error': e.args})


class UpdateMy(APIView):
    def post(self, request, *args, **kwargs):
        try:
            token = request.META.get('HTTP_AUTHORIZATION')
            id = get_user_id(token)
            user = User.objects.filter(status=1, id=id).first()
            user.name = request.data.get('name')
            user.tel = request.data.get('tel')
            user.email = request.data.get('email')

            user.save()

            return Response({'status': 200, 'msg': '修改成功'})
        except Exception as e:
            return Response({'status': 204, 'msg': '遇到了异常错误', 'error': e.args})
